<template>
    <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
               :close-on-press-escape="false">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
                 :label-width="$i18n.locale === 'en-US' ? '120px' : '100px'">
            <el-form-item label="商品名称" prop="commodityName">
                <el-input v-model="dataForm.commodityName" placeholder="商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品市场价" prop="commodityMarketPrice">
                <el-input v-model="dataForm.commodityMarketPrice" placeholder="商品市场价"></el-input>
            </el-form-item>
            <el-form-item label="店铺价格" prop="shopPrice">
                <el-input v-model="dataForm.shopPrice" placeholder="店铺价格"></el-input>
            </el-form-item>
            <el-form-item label="商品图片" prop="commodityPic">
                <el-upload
                        class="avatar-uploader"
                        :action="url"
                        :show-file-list="false"
                        :on-success="successHandle"
                        :before-upload="beforeUploadHandle">
                    <img v-if="dataForm.commodityPic" :src="commodityPic" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="商品详情" prop="commodityDetails">
                <!-- 富文本编辑器, 容器 -->
                <div id="J_quillEditor"></div>
                <!-- 自定义上传图片功能 (使用element upload组件) -->
                <el-upload
                        :action="uploadUrl"
                        :show-file-list="false"
                        :before-upload="uploadBeforeUploadHandle"
                        :on-success="uploadSuccessHandle"
                        style="display: none;">
                    <el-button ref="uploadBtn" type="primary" size="small">{{ $t('upload.button') }}</el-button>
                </el-upload>
            </el-form-item>
        </el-form>
        <template slot="footer">
            <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
        </template>
    </el-dialog>
</template>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
<script>
    import debounce from 'lodash/debounce'
    import Cookies from "js-cookie";
    import 'quill/dist/quill.snow.css'
    import Quill from 'quill'

    export default {
        data() {
            return {
                visible: false,
                commodityPic: '',
                dataForm: {
                    id: '',
                    commodityName: '',
                    commodityMarketPrice: '',
                    shopPrice: '',
                    commodityPic: '',
                    commodityDetails: ''
                },
                //图片上传
                url: '',
                num: 0,
                fileList: [],
                //富文本
                quillEditor: null,
                quillEditorToolbarOptions: [
                    ['bold', 'italic', 'underline', 'strike'],
                    ['blockquote', 'code-block', 'image'],
                    [{'header': 1}, {'header': 2}],
                    [{'list': 'ordered'}, {'list': 'bullet'}],
                    [{'script': 'sub'}, {'script': 'super'}],
                    [{'indent': '-1'}, {'indent': '+1'}],
                    [{'direction': 'rtl'}],
                    [{'size': ['small', false, 'large', 'huge']}],
                    [{'header': [1, 2, 3, 4, 5, 6, false]}],
                    [{'color': []}, {'background': []}],
                    [{'font': []}],
                    [{'align': []}],
                    ['clean']
                ],
                uploadUrl: ''
            }
        },
        computed: {
            dataRule() {
                var validateContent = (rule, value, callback) => {
                    if (this.quillEditor.getLength() <= 1) {
                        return callback(new Error(this.$t('validate.required')))
                    }
                    callback()
                }
                return {
                    commodityName: [
                        {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                    ],
                    commodityMarketPrice: [
                        {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                    ],
                    shopPrice: [
                        {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                    ],
                    commodityPic: [
                        { required: true, message: this.$t('validate.required'), trigger: 'blur' },
                        { validator: validateContent, trigger: 'blur' }
                    ],
                    commodityDetails: [
                        {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            init() {
                this.visible = true
                this.url = `${window.SITE_CONFIG['apiURL']}/sys/oss/myUpload?token=${Cookies.get('token')}`
                this.num = 0
                this.fileList = []
                this.$nextTick(() => {
                    if (this.quillEditor) {
                        this.quillEditor.deleteText(0, this.quillEditor.getLength())
                    } else {
                        this.quillEditorHandle()
                    }
                    this.$refs['dataForm'].resetFields()
                    if (this.dataForm.id) {
                        this.getInfo()
                    }
                })
            },
            // 上传之前
            beforeUploadHandle(file) {
                if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
                    this.$message.error(this.$t('upload.tip', {'format': 'jpg、png、gif'}))
                    return false
                }
                this.num++
            },
            // 上传成功
            successHandle(res, file, fileList) {
                if (res.code !== 0) {
                    return this.$message.error(res.msg)
                }
                this.fileList = fileList
                this.num--
                if (this.num === 0) {
                    this.$message({
                        message: this.$t('prompt.success'),
                        type: 'success',
                        duration: 500
                    })
                    this.dataForm.commodityPic = res.data.src
                    this.commodityPic = this.imgUrl + res.data.src
                }
            },
            // 富文本编辑器
            quillEditorHandle () {
                this.quillEditor = new Quill('#J_quillEditor', {
                    modules: {
                        toolbar: this.quillEditorToolbarOptions
                    },
                    theme: 'snow'
                })
                // 自定义上传图片功能 (使用element upload组件)
                this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/sys/oss/myUpload?token=${Cookies.get('token')}`
                this.quillEditor.getModule('toolbar').addHandler('image', () => {
                    this.$refs.uploadBtn.$el.click()
                })
                // 监听内容变化，动态赋值
                this.quillEditor.on('text-change', () => {
                    this.dataForm.commodityDetails = this.quillEditor.root.innerHTML
                })
            },
            // 上传图片之前
            uploadBeforeUploadHandle (file) {
                if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
                    this.$message.error('只支持jpg、png、gif格式的图片！')
                    return false
                }
            },
            // 上传图片成功
            uploadSuccessHandle (res, file, fileList) {
                if (res.code !== 0) {
                    return this.$message.error(res.msg)
                }
                this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', this.imgUrl + res.data.src)
            },
            // 获取信息
            getInfo() {
                this.$http.get(`/demo/xlscommodity/${this.dataForm.id}`).then(({data: res}) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg)
                    }
                    this.dataForm = {
                        ...this.dataForm,
                        ...res.data
                    }
                    this.commodityPic = this.imgUrl + this.dataForm.commodityPic
                    this.quillEditor.root.innerHTML =  this.dataForm.commodityDetails
                }).catch(() => {
                })
            },
            // 表单提交
            dataFormSubmitHandle: debounce(function () {
                this.$refs['dataForm'].validate((valid) => {
                    if (!valid) {
                        return false
                    }
                    this.$http[!this.dataForm.id ? 'post' : 'put']('/demo/xlscommodity/', this.dataForm).then(({data: res}) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.msg)
                        }
                        this.$message({
                            message: this.$t('prompt.success'),
                            type: 'success',
                            duration: 500,
                            onClose: () => {
                                this.visible = false
                                this.$emit('refreshDataList')
                            }
                        })
                    }).catch(() => {
                    })
                })
            }, 1000, {'leading': true, 'trailing': false})
        }
    }
</script>
